package com.android.base.tools.codec;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class MAC {
    /**
     * 初始化HMAC密钥
     *
     * @param algorithm 算法，可为空。默认为：Algorithm.Hmac_MD5
     * @return
     * @throws Exception
     */
    public static String initMacKey(Algorithm algorithm) throws Exception {
        if (algorithm == null) algorithm = Algorithm.Hmac_MD5;
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm.getType());
        SecretKey secretKey = keyGenerator.generateKey();

        return BASE64.encodeToString(secretKey.getEncoded());
    }

    /**
     * HMAC加密
     *
     * @param plain     明文
     * @param key       key
     * @param algorithm 算法，可为空。默认为：Algorithm.Hmac_MD5
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] plain, String key, Algorithm algorithm) throws Exception {
        if (algorithm == null) algorithm = Algorithm.Hmac_MD5;
        SecretKey secretKey = new SecretKeySpec(BASE64.decode(key), algorithm.getType());
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);

        return mac.doFinal(plain);
    }
}